<template>
	<div
		style="border: 1px solid rgba(0, 0, 0, 0.1); position: relative; overflow-y: scroll"
		:style="{
			height: height,
		}"
	>
		<Toolbar :editor="editor" v-if="!preview" style="position: sticky; top: 0; z-index: 99"></Toolbar>
		<Editor
			@onCreated="createEditor"
			:mode="'simple'"
			@onChange="editorChange"
			:style="{
				minHeight: '330px',
			}"
			:defaultConfig="{
				readOnly: preview,
				MENU_CONF: {
					uploadImage: {
						server: '/admin/ajax/upload',
						fieldName: 'file',
						maxFileSize: 1024 * 1024 * 4,
						headers: {
							batoken: this.$store.state.token,
						},
						customInsert: this.customInsert,
						onFailed: uploadErr,
						onError: uploadErr,
					},
					uploadVideo: {
						server: '/admin/ajax/upload',
						fieldName: 'file',
						maxFileSize: 1024 * 1024 * 10,
						headers: {
							batoken: this.$store.state.token,
						},
						customInsert: this.customInsert,
					},
				},
				placeholder: '请输入项目详情',
				autoFouces: false,
				scroll: true,
			}"
		></Editor>
	</div>
</template>
<script>
import { Editor, Toolbar } from "@wangeditor/editor-for-vue"
export default {
	data() {
		return {
			editor: null,
		}
	},
	components: {
		Editor,
		Toolbar,
	},
	props: {
		value: String,
		preview: Boolean,
		height: {
			type: String,
			default: "auto",
		},
	},
	watch: {
		value: {
			handler(value) {
				this.setHtml(value)
			},
			deep: true,
			immediate: true,
		},
	},
	methods: {
		uploadErr(err) {
			if (err.size / 1024 / 1024 > 4) {
				this.$message.error("图片大小不能超过2M")
				return
			}
		},
		setHtml(value) {
			this.$nextTick(() => {
				if (this.editor) {
					this.editor.setHtml(value)
				} else {
					this.setHtml(value)
				}
			})
		},
		createEditor(editor) {
			this.editor = Object.seal(editor)
		},
		// 监听editor改变
		editorChange() {
			if (this.editor) {
				this.$emit("input", this.editor.getHtml())
			}
		},
		// Editor自定义插入图片
		customInsert(res, insertFn) {
			let file = res.data.file
			insertFn(this.$store.getters.baseUrl + file.url, file.name, this.$store.getters.baseUrl + file.url)
		},
	},
}
</script>
<style>
@import "@wangeditor/editor/dist/css/style.css";
</style>
